package qc.module.iot.api.job;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import qc.common.core.enums.iot.IotPacketsFrameFlagEnum;
import qc.common.core.utils.RadixConvertUtil;
import qc.module.iot.dto.MqIotPacketsMessageDto;
import qc.module.iot.entity.IotFramePackets;
import qc.module.iot.service.IotFramePacketsService;
import qc.module.iot.service.producer.IotFramePacketsProducer;
import tech.powerjob.worker.core.processor.ProcessResult;
import tech.powerjob.worker.core.processor.TaskContext;
import tech.powerjob.worker.core.processor.sdk.BasicProcessor;

import java.util.List;

/**
 * 获取待发送至MQ的报文数据帧记录Processor，发送至MQ进行解析
 *
 * @author QuCheng Tech
 * @since 2025/11/19
 */
@Component
public class GetNeedParseFrameJobProcessor implements BasicProcessor {
    private static final Logger logger = LoggerFactory.getLogger(GetNeedParseFrameJobProcessor.class);

    @Autowired
    private IotFramePacketsProducer iotPacketsProducer;

    @Autowired
    IotFramePacketsService service;

    @Override
    public ProcessResult process(TaskContext taskContext) throws Exception {
        logger.debug("process taskContext.getJobParams=" + taskContext.getJobParams());

        //一次获取待解析数据帧最大数量，从PowerJob中的任务参数中获取，如果没有设置使用默认值
        int maxCount = 0x0;
        String jobParams = taskContext.getJobParams();
        if (StringUtils.isNotBlank(jobParams)) {
            //时段类型字符串转换为int，后继可以扩展任务参数为json格式
            try {
                int intValue = Integer.parseInt(jobParams);
                if (intValue > 0x0)
                    maxCount = intValue;
            } catch (NumberFormatException e) {

            }
        }

        try {
            List<IotFramePackets> framePackets = service.getNeedSendToMQPackets(maxCount);
            if (framePackets != null && framePackets.size() > 0x0) {
                logger.debug("本次共取出数据帧报文记录[{}]条。", framePackets.size());

                for (IotFramePackets frame : framePackets) {
                    MqIotPacketsMessageDto message = new MqIotPacketsMessageDto();
                    message.setId(frame.getId());
                    message.setIntm(frame.getIntm());
                    //十六进制字符串自行进行转换，只能使用hex进行存储以保证再次解析为byte数组能保持一致
                    String hexString = frame.getHex();
                    message.setHex(hexString);
                    message.setBytes(RadixConvertUtil.hexStringToBytes(hexString));
                    //信道ID保持为null，只需要在接收数据时进行赋值更新信道的最新时间
                    message.setChannelId(null);
                    //需要通道类型枚举值，因为调用原始数据保存接口时需要传入数据的来源通道类型
                    message.setChannelType(frame.getChanneltype());
                    message.setChannelName(frame.getChannelname());
                    message.setDataProtocol(frame.getDataprotocol());
                    message.setFrameType(frame.getFrametype());
                    message.setFrameName(frame.getFramename());
                    message.setStcd(frame.getStcd());
                    //设置标记为已发送至MQ
                    message.setFlag(IotPacketsFrameFlagEnum.SENDED.getIndex());
                    //设置消息的来源是从数据库中查询出的记录，在消费者中进行判断处理（保存至数据库消费者在标记为true时不需要重复进行保存）
                    message.setFromDb(true);

                    // 同步发送，等待Broker响应
                    String sendResult = iotPacketsProducer.syncSend(message);
                    if (StringUtils.isBlank(sendResult)) {
                        //发送消息至MQ成功
                    } else {
                        //发送消息至MQ失败
                        logger.error("发送数据帧报文记录消息至MQ失败，记录ID[{}]，失败提示信息[{}]", frame.getId(), sendResult);
                    }
                }
            }
        } catch (Exception ex) {
            logger.error("定时任务获取待解析数据帧报文时异常，提示信息[{}]", ex.getMessage());
        }

        return new ProcessResult(true, "成功");
    }
}
